<template>
  <div>
    <a-modal
      :visible="visible"
      title="添加检查反馈单"
      cancelText="返回"
      @cancel="cancel"
      width="calc(100% - 240px)"
      :style="{top: '0px', 'margin-left': '240px', maxWidth: '100vw', height: 'calc(100% - 132px)'}"
    >
      <template v-slot:footer>
        <div style="text-align: center;">
          <a-button style="background-color: forestgreen; margin-left: 5px; color: white;" @click="subSave">保存</a-button>
          <a-button type="primary" @click="submit">提交</a-button>
          <a-button @click="cancel">返回</a-button>
        </div>
      </template>
      <a-form
        id="infoDIV"
        ref="formRef"
        layout="inline"
        :model="formState"
        :rules="formRules"
      >
        <a-row style="width: 100%; height: 56px;">
          <a-form-item label="项目类型" ref="xmflei" name="xmflei">
            <a-select v-model:value="formState.xmflei" placeholder="请选择项目类型" style="width: 250px;" @change="changeSelect">
              <a-select-option value="">请选择项目类型</a-select-option>
              <a-select-option value="重大水利工程">重大水利工程</a-select-option>
              <a-select-option value="主要支流治理">主要支流治理</a-select-option>
              <a-select-option value="大中型病险水库除险加固">大中型病险水库除险加固</a-select-option>
              <a-select-option value="大中型病险水闸除险加固">大中型病险水闸除险加固</a-select-option>
              <a-select-option value="新建中型水库工程">新建中型水库工程</a-select-option>
              <a-select-option value="新建小型水库工程">新建小型水库工程</a-select-option>
              <a-select-option value="小型病险水库除险加固">小型病险水库除险加固</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="项目名称" ref="xmid" name="xmid">
            <a-select v-model:value="formState.xmid" style="width: 579px;" @change="doChangexmxx">
              <a-select-option
                :value="xmxx.id"
                :xmfr="xmxx.xmfr"
                :cjdw="xmxx.zhongbiaoren"
                :shimc="xmxx.shimc"
                :xianmc="xmxx.xianmc"
                :shi="xmxx.shi"
                :xian="xmxx.xian"
                :xmfrid="xmxx.xmfrid"
                v-bind:key="index"
                v-for="(xmxx,index) in state.xmxxs"
              >{{xmxx.xmmc}}</a-select-option>
            </a-select>
            <input type="hidden" id="xmmc" name="xmmc">
          </a-form-item>
          <a-form-item label="所在市" ref="shimc" name="shimc">
            <a-input v-model:value="formState.shimc" style="width: 200px"/>
            <input type="hidden" id="shi" name="shi">
          </a-form-item>
          <a-form-item label="所在县" ref="xianmc" name="xianmc">
            <a-input v-model:value="formState.xianmc" style="width: 200px"/>
            <input type="hidden" id="xian" name="xian">
          </a-form-item>
        </a-row>

        <a-row style="width: 100%; height: 56px;">
          <a-form-item label="项目法人" ref="xmfren" name="xmfren">
            <a-input v-model:value="formState.xmfren" style="width: 250px"/>
            <input type="hidden" id="xmfrid" name="xmfrid">
          </a-form-item>
          <a-form-item label="参建单位" ref="cjdwei" name="cjdwei">
            <a-input v-model:value="formState.cjdwei" style="width: 829px"/>
          </a-form-item>
          <a-form-item label="质量监督单位" ref="qsdwei" name="qsdwei">
            <a-input v-model:value="formState.qsdwei" style="width: 190px"/>
          </a-form-item>
        </a-row>

        <a-row style="width: 100%; height: 120px;">
          <a-form-item label="主要问题" ref="fxzywtqk" name="fxzywtqk">
            <a-textarea v-model:value="formState.fxzywtqk" style="width: 1478px; height: 100px;" @focus="getFocusArea('fxzywtqk')" @keyup="getKeyupFxwt($event)"/>
          </a-form-item>
        </a-row>

        <a-row style="width: 100%; height: 100%;">
          <a-form-item label="问题照片">
            <div>
              <a-upload
                :action="actionUrl"
                :multiple="true"
                v-model:file-list="fileListPhotos"
                :headers="headers"
                accept="image/*"
                @preview="handlePreview"
                class="xmjcfile"
                :customRequest="uploadImages"
              >
                <a-button type="primary">
                  <upload-outlined></upload-outlined>
                  上传问题照片
                </a-button>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
              <a-input type="hidden" v-model:value="formState.photo" id="photo" name="photo"/>
            </div>
          </a-form-item>
        </a-row>

        <a-row style="width: 100%; height: 120px;">
          <a-form-item label="意见建议" ref="gzyjjyqk" name="gzyjjyqk">
            <a-textarea v-model:value="formState.gzyjjyqk" style="width: 1478px; height: 100px;" @focus="getFocusArea('gzyjjyqk')" @keyup="getKeyupYjjy($event)"/>
          </a-form-item>
        </a-row>

        <a-row style="width: 100%; height: 56px;">
          <a-form-item label="完成时限" ref="wcsxian" name="wcsxian">
            <a-date-picker v-model:value="formState.wcsxian" valueFormat="YYYY-MM-DD" id="wcsxian" name="wcsxian"/>
          </a-form-item>
          <a-form-item label="检查单位" ref="jcdwei" name="jcdwei">
            <a-input v-model:value="formState.jcdwei" style="width: 419px"/>
          </a-form-item>
          <a-form-item label="检查人" ref="inspectors" name="inspectors">
            <a-input v-model:value="formState.inspectors" style="width: 419px"/>
          </a-form-item>
          <a-form-item label="检查时间" ref="jcsjian" name="jcsjian">
            <a-date-picker v-model:value="formState.jcsjian" valueFormat="YYYY-MM-DD" id="jcsjian" name="jcsjian"/>
          </a-form-item>
        </a-row>

        <a-row style="width: 100%; height: 100%;">
          <a-form-item label="检查文件">
            <div>
              <a-upload
                :action="actionUrl"
                :multiple="true"
                v-model:file-list="fileListFujian"
                :headers="headers"
                accept=".jpg, .jpeg, .png, .pdf, .doc, .docx, .wps"
                class="xmjcfile"
                :customRequest="uploadFile"
              >
                <a-button type="primary">
                  <upload-outlined></upload-outlined>
                  上传文件
                </a-button>
              </a-upload>
              <a-input type="hidden" v-model:value="formState.fujian" id="fujian" name="fujian"/>
            </div>
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import {xmlist, save, upload} from '@/api/module/xmjcha';
import {profile} from '@/api/module/user';
import {getdept} from "@/api/module/dept";
import {defineComponent, reactive, ref, toRaw, watch} from "vue";
import $ from "jquery";
import {message} from "ant-design-vue";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    }
  },
  emit: ["close"],
  setup(props, context) {
    const formRef = ref();

    const state = reactive({
      xmxxs: [],
    })

    const formState = reactive({
    });

    const formRules = {
      xmflei: [
        { required: true, message: '请选择项目类型', trigger: 'change'},
      ],
      xmid: [
        { required: true, message: '请选择项目', trigger: 'change'},
      ],
      xmfren: [
        { required: true, message: '请完善信息填报内的法人数据', trigger: 'blur'},
      ],
      wcsxian: [
        { required: true, message: '请选择完成时限',},
      ],
      jcdwei: [
        { required: true, message: '请选输入检查单位', trigger: 'blur'},
      ],
      jcsjian: [
        { required: true, message: '请选择检查时间',},
      ],
    };

    ///提交
    const submit = (e) => {
      formState.dataztai = '0';
      formRef.value.validate().then(() => {
        save(toRaw(formState)).then((response)=>{
          if(response.success){
            message.success({ content: '提交成功', duration: 1 }).then(()=>{
              cancel();
            });
          }else{
            message.error({ content: '提交失败', duration: 1 }).then(()=>{
              cancel();
            });
          }
        })
      }).catch(error => {
        console.log('error', error);
      });
    };

    ///保存
    const subSave = (e) => {
      console.log(e)
      formState.dataztai = '1';
      formRef.value.validate().then(() => {
        save(toRaw(formState)).then((response)=>{
          if(response.success){
            message.success({ content: '保存成功', duration: 1 }).then(()=>{
              $("#reloadbtn").click();
              cancel();
            });
          }else{
            message.error({ content: '保存失败', duration: 1 }).then(()=>{
              cancel();
            });
          }
        })
      }).catch(error => {
        console.log('error', error);
      });
    };

    const cancel = (e) => {
      formRef.value.resetFields();
      context.emit("close", false);
    };

    var options;
    const changeSelect = function (value) {
      formState.xmid = '';
      formState.xmmc = '';
      formState.shimc = '';
      formState.shi = '';
      formState.xianmc = '';
      formState.xian = '';
      formState.xmfren = '';
      formState.xmfrid = '';
      formState.cjdwei = '';

      xmlist({'report_index': value}).then((response) => {
        state.xmxxs = response.data;
        //console.log(state.xmxxs)
        options = ref(state.xmxxs)
      })
    };

    const doChangexmxx = function (value){
      const selectedOption = options.value.find(xmxx => xmxx.id === value);
      formState.xmmc = selectedOption.xmmc;
      formState.shimc = selectedOption.shimc;
      formState.shi = selectedOption.shi;
      formState.xianmc = selectedOption.xianmc;
      formState.xian = selectedOption.xian;
      formState.xmfren = selectedOption.xmfr;
      formState.xmfrid = selectedOption.xmfrid;
      formState.cjdwei = selectedOption.dfjb;
    }

    /// 修改内容
    const getFocusArea = (id) => {
      var _val = $("#"+ id).val();
      if (0 >= _val.length) {
        $("#"+ id).val("1. ");
      }
    };

    ///回车事件
    var wtcount = 1;
    const getKeyupFxwt = (e) => {
      if (e.keyCode == 13) {
        var content = $("#fxzywtqk").val();
        wtcount = wtcount +1;
        $("#fxzywtqk").val(content + wtcount +". ");
      }
    }
    var jycount = 1;
    const getKeyupYjjy = (e) => {
      if (e.keyCode == 13) {
        var content = $("#gzyjjyqk").val();
        jycount = jycount +1;
        $("#gzyjjyqk").val(content + jycount +". ");
      }
    }

    const loadwindows = () => {
      profile({}).then((response) => {
        formState.inspectors = response.data.nickname;
        getdept({'id': response.data.deptId}).then((response) => {
          formState.jcdwei = response.data.name
        })
      });
    }

    loadwindows();

    const tokenKey = localStorage.getItem("token_key");
    const token = localStorage.getItem("token")

    const headers = {
      "Authorization": token,
      "Authorization-key": tokenKey
    };

    const fileListPhotos = ref([]);
    const fileListFujian = ref([]);

    const previewVisible = ref(false);
    const previewImage = ref('');

    const handlePreview = async file => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
    };

    const handleCancel = () => {
      previewVisible.value = false;
    };

    const actionUrl = () => {
      return "http://localhost:9292/api/project/xmjc/upload";
    }

    const uploadImages = async (e) => {
      const form = new FormData();
      form.append('file', e.file);
      const res = await upload(form);
      if (res){
        e.onSuccess(res.data, e);
        var phototemp = $("#photo").val();
        var photoValue = "";
        if ("" === phototemp || null === phototemp){
          photoValue = res.data.fileName;
        } else {
          photoValue = phototemp +","+ res.data.fileName;
        }
        formState.photo = photoValue;
      }
    }

    const uploadFile = async (e) => {
      const form = new FormData();
      form.append('file', e.file);
      const res = await upload(form);
      if (res){
        e.onSuccess(res.data, e);
        var fujiantemp = $("#fujian").val();
        var fujianValue = "";
        if ("" === fujiantemp || null === fujiantemp){
          fujianValue = res.data.fileName;
        } else {
          fujianValue = fujiantemp +"#"+ res.data.fileName;
        }
        formState.fujian = fujianValue;
      }
    }

    return {
      state,
      submit,
      subSave,
      cancel,
      formRef,
      formState,
      formRules,

      changeSelect,
      getFocusArea,
      getKeyupFxwt,
      getKeyupYjjy,
      doChangexmxx,

      headers,
      fileListPhotos,
      fileListFujian,
      previewVisible,
      previewImage,
      handlePreview,
      handleCancel,
      actionUrl,
      uploadImages,
      uploadFile,

      /*labelCol: { span: 5 },
      wrapperCol: { span: 8 },*/

    };
  },
});
</script>
<style scoped>
  /* ::v-deep .ant-modal-content{
    height: calc(100% - -92px);
  } */

  /* tile uploaded pictures */
  .xmjcfile :deep(.ant-upload-list) {
    width: 1478px;
    margin-bottom: 20px;
  }
</style>
